﻿using AutoMapper;
using MediatR;
using ProductionManagement.Application.Command.FeedingCommand;
using ProductionManagement.Domain.ProductionDomain;
using ProductionManagement.Infrstructre.lnterface;
using SqlSugar;

namespace ProductionManagement.Application.CommandHandler.FeedingCommandHandler
{
    public class UpdFeedProductCommandHandler : IRequestHandler<UpdFeedProductCommand, int>
    {

        IFeedingRepository fRep;
        IFeedProductRepository fpRep;
        IMapper mapper;
        ISqlSugarClient db;

        public UpdFeedProductCommandHandler(IMapper mapper,
        ISqlSugarClient db, IFeedingRepository fRep,
        IFeedProductRepository fpRep)
        {
            this.mapper = mapper;
            this.db = db;
            this.fRep = fRep;
            this.fpRep = fpRep;
        }

        public async Task<int> Handle(UpdFeedProductCommand request, CancellationToken cancellationToken)
        {
            // 开始事务
            db.Ado.BeginTran();

            try
            {
                //修改生产补料
                var se = await db.Queryable<Feeding>()
                                 .Where(c => c.FeedingId == request.UpdDto.FeedingId)
                .FirstAsync();

                var procurement1 = mapper.Map<Feeding>(request.UpdDto);
                var taskToAdd = await fRep.UpdAsync(procurement1);


                //删除采购退货中的数据
                var itemsToDelete = await db.Queryable<FeedProduct>()
                                  .Where(c => c.FeNumber == se.FeNumber)
                                  .ToListAsync();
                foreach (var item in itemsToDelete)
                {
                    await fpRep.DelRange(new List<FeedProduct> { item });
                }


                //修改采购退货产品
                foreach (var item in request.UpdDto.feedingProducts)
                {
                    FeedProduct detail = new FeedProduct();
                    detail.ProductId = item.ProductId;
                    detail.FeNumber = se.FeNumber;
                    detail.FePNum = item.FePNum;
                    detail.ManpowerId = item.ManpowerId;
                    detail.FePDeliveryDate = item.FePDeliveryDate;
                    detail.Office_Id = item.Office_Id;
                    detail.User_Id = item.User_Id;
                    await fpRep.AddAsync(detail);
                }

                // 提交事务
                db.Ado.CommitTran();

                return 1;  // 返回最终的结果
            }
            catch (Exception)
            {
                // 回滚事务
                db.Ado.RollbackTran();
                throw;
            }
        }

    }
}
